package com.bdzl.auth.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.bdzl.auth.service.RoleService;
import com.bdzl.pub.common.Tree;
import com.bdzl.pub.controller.BaseController;
import com.bdzl.pub.entity.sys.RoleDO;
import com.bdzl.pub.string.StringUtils;
import com.bdzl.pub.vo.sys.MeauVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.bdzl.pub.entity.sys.MeauDO;
import com.bdzl.auth.service.MeauService;
import com.bdzl.pub.util.param.R;

/**
 * 系统菜单表
 * 
 * @author yangyicai
 * @email yangyicai@foxmail.com
 * @date 2021-03-23 13:59:22
 */
 
@Controller
@RequestMapping("/bdzl/meau")
public class MeauController extends BaseController {
	@Autowired
	private MeauService meauService;
	@Autowired
	private RoleService roleService;
	
	@GetMapping()
	String Meau(){
	    return "bdzl/meau/meau";
	}

	/**
	 * 查询
	 */
	@RequestMapping("/list")
	@ResponseBody
	List<MeauVO> list(@RequestBody Map<String,Object> map) {
		if(map.get("searchWord")==null) {
			map.remove("searchWord");
		}
		//查询所有数据
		map.put("noButton",1);
		List<MeauVO> menus = meauService.voList(map);
		//所有目录的id
		List<String> menuIds = new ArrayList<>();

		menus.forEach(ele->{
			if (ele.getMeauType().equals("1")) {
				menuIds.add(ele.getMenuId());
			}
		});
		if (StringUtils.isEmpty(menuIds)) {
			return menus;
		}
		//根据pid进行分组
		Map<String, List<MeauDO>> collect = meauService.getMenuByPid(menuIds).stream().collect(Collectors.groupingBy(MeauDO::getMenuPid));
		menus.forEach(ele -> {
			if (ele.getMeauType().equals("1")) {
				List<MeauDO> menuDOS = collect.get(ele.getMenuId());
				if (StringUtils.isNotEmpty(menuDOS)) {
					List<String> collect1 = menuDOS.stream().map(MeauDO::getMeauName).collect(Collectors.toList());
					ele.setButtonType(collect1);
				}
			}
		});
		return menus;
	}
	
	@GetMapping("/add")
	String add(){
	    return "bdzl/meau/add";
	}

	@PostMapping("/edit")
	@ResponseBody
	R edit(@RequestBody MeauDO mdo){
		mdo = meauService.get(mdo.getMenuId());
		List<String> ids = new ArrayList<>();
		ids.add(mdo.getMenuId());
		//类拷贝
		MeauVO meauVO  = new MeauVO();
		BeanUtils.copyProperties(mdo, meauVO);
		//拿到所有的按钮数据
		List<MeauDO> menuByPid = meauService.getMenuByPid(ids);
		meauVO.setMenuDOList(menuByPid);
		String pId = mdo.getMenuPid();

		R r = R.ok();
		r.put("pId", pId);
		if (mdo.getMenuPid().equals("-1")){
			r.put("pName","根目录");
		}else {
			MeauDO meauDO = meauService.get(mdo.getMenuPid());
			r.put("pName", meauDO.getMeauName());
		}
		r.put("menu", meauVO);
		return r;
	}


/**
 * @Author Zhn
 * @Description //TODO 保存菜单
 * @Date 15:32 2021/5/14
 * @Param [menuDOList]
 * @return com.bdzl.pub.util.param.R
 **/
	@PostMapping("/save")
	@ResponseBody
	@Transactional
	public R save(@RequestBody List<MeauDO> menuDOList) {
		int r = 0;
		int id = 0;
		for (MeauDO menuDO : menuDOList) {
			if (!menuDO.getMeauType().equals("2")){
				r= meauService.add(menuDO);
			}else if (menuDO.getMeauType().equals("2")){
				id++;
				String format = String.format("%02d", id);
				menuDO.setMenuId(menuDO.getMenuPid()+"_"+format+"b");
				r= meauService.add(menuDO);
			}
			if (r==-1){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error("菜单编号重复");
			}else if (r==-2){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error("菜单编号不合法，请以'"+menuDO.getMenuPid()+"_'开头");
			}else if (r==-3){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error("添加失败");
		}
		}
		return R.ok();
	}
	/**
	 * @Author Zhn
	 * @Description //TODO 菜单更新
	 * @Date 15:46 2021/5/14
	 * @Param [menuDOList] 菜单列表
	 * @return com.bdzl.pub.util.param.R
	 **/
	@PostMapping("/update")
	@ResponseBody
	@Transactional
	public R update(@RequestBody List<MeauDO> menuDOList) {
		int r = 0;
		int id = 0;
		int i = 0;
		for (MeauDO menuDO : menuDOList) {
			if (menuDO.getMenuId()!=null){
				if (meauService.update(menuDO)>0){
					r++;
				}
			}else {
				boolean verify;
				String format;
				do {
					id++;
					format = String.format("%02d", id);
					verify = meauService.verify(menuDO.getMenuPid() + "_" + format + "b");
				}while (verify);
				menuDO.setMenuId(menuDO.getMenuPid() + "_" + format + "b");
				i= meauService.add(menuDO);
				if (i==-1){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("菜单编号重复");
				}else if (i==-2){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("菜单编号不合法，请以'"+menuDO.getMenuPid()+"_'开头");
				}
			}
		}
		if (r>0){
			return R.ok();
		}else {
			return R.error();
		}
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public R update( MeauDO meau){
		meauService.update(meau);
		return R.ok();
	}

	/**
	 * @Author Zhn
	 * @Description //TODO 删除菜单
	 * @Date 15:50 2021/5/14
	 * @Param [id] 菜单ID
	 * @return com.bdzl.pub.util.param.R
	 **/
	@PostMapping("/remove")
	@ResponseBody
	public R remove(@RequestBody MeauDO menuDO) {
		String id = menuDO.getMenuId();
		List<String> ids = new ArrayList<>();
		ids.add(id);
		menuDO = meauService.get(id);
		if (menuDO.getMeauType().equals("0")){
			List<MeauDO> menuByPid = meauService.getMenuByPid(ids);
			if (menuByPid.size()!=0){
				return R.error("存在下级菜单，无法删除");
			}else {
				meauService.remove(id);
				meauService.removeByPid(id);
			}
		} else if (menuDO.getMeauType().equals("1")){
			List<MeauDO> menuByPid = meauService.getMenuByPid(ids);
			if (menuByPid.size()!=0){
				return R.error("存在按钮，无法删除");
			}else {
				meauService.remove(id);
				meauService.removeByPid(id);
			}
		} else if (menuDO.getMeauType().equals("2")){
			meauService.remove(id);
		}
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	public R remove(@RequestParam("ids[]") String[] menuIds){
		meauService.batchRemove(menuIds);
		return R.ok();
	}


	/**
	 * 用户管理--角色管理--编辑
	 * @param roleId 角色id
	 * @return
	 */
	@GetMapping("/tree")
	@ResponseBody
	Map<String, Object> tree(String roleId, String type) {
		Integer[] roleIds=roleService.userRoles(super.getUserId()).stream().map(RoleDO::getRoleId).toArray(Integer[]::new);
		return meauService.getTree(roleIds,type,roleId,1);
	}
	
}
